export default function remoteLoad(url: string, hasCallback?: any): Promise<void> {
  return createScript(url)

  function createScript(url: string) {
    let scriptElement = document.createElement('script')
    document.body.appendChild(scriptElement)
    //加载完成后
    function loadFn(resolve: any, e: Event) {
      removeScript(scriptElement)
      if (!hasCallback) {
        resolve(e)
      }
    }

    let promise = new Promise<void>((resolve, reject) => {
      scriptElement.addEventListener(
        'load',
        e => {
          loadFn(resolve, e)
        },
        false
      )

      scriptElement.addEventListener(
        'error',
        e => {
          removeScript(scriptElement)
          reject(e)
        },
        false
      )

      if (hasCallback) {
        window.____callback____ = function () {
          resolve()
          window.____callback____ = null
        }
      }
    })

    if (hasCallback) {
      url += '&callback=____callback____'
    }

    scriptElement.src = url
    return promise
  }

  function removeScript(scriptElement: HTMLScriptElement) {
    document.body.removeChild(scriptElement)
  }
}

